package com.cus.tom.transfer.adapter;

import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.databinding.AppItemBinding;
import com.cus.tom.transfer.frag.AppFragment;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AppAdapter extends RecyclerView.Adapter {

    List<ApplicationInfo> list;
    Set<String> set = new HashSet<>();
    AppFragment fragment;

    public AppAdapter(List<ApplicationInfo> list, AppFragment fragment) {
        this.list = list;
        this.fragment = fragment;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        AppItemBinding binding = AppItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        AppItemBinding binding;

        Holder(AppItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            ApplicationInfo item = list.get(p);
            Drawable d = item.loadIcon(App.getApp().getPackageManager());
            binding.img.setImageDrawable(d);
            binding.name.setText(item.loadLabel(App.getApp().getPackageManager()).toString());
            itemView.setOnClickListener(v -> {
                boolean bo = !binding.check.isSelected();
                binding.check.setSelected(bo);
                if (bo) {
                    set.add(item.packageName);
                } else {
                    set.remove(item.packageName);
                }
                fragment.update();
            });
            binding.check.setSelected(set.contains(item.packageName));
        }
    }

    public Set<String> getSelect() {
        return set;
    }

    public void selectAll(boolean bo) {
        if (bo) {
            set.clear();
            for (ApplicationInfo info : list) {
                set.add(info.packageName);
            }
        } else {
            set.clear();
        }
        notifyItemRangeChanged(0, list.size());
    }

    public void setSelect(Set set) {
        this.set.clear();
        this.set.addAll(set);
        notifyItemRangeChanged(0, list.size());
    }
}
